//
//  Tweet.m
//  Echo
//
//  Created by Liao on 14/12/16.
//  Copyright (c) 2014年 sina. All rights reserved.
//

#import "Tweet.h"
#import "User.h"
#import "Pic.h"
#import "BaseApiClient.h"
#import "Collecton.h"
#import "CurrentUser.h"

@implementation Tweet

@synthesize mid = _mid;
@synthesize cate = _cate;
@synthesize owner = _owner;
@synthesize text = _text;
@synthesize pic_nums = _pic_nums;
@synthesize pics = _pics;
@synthesize created_time = _created_time;
@synthesize is_collected = _is_collected;

- (instancetype)initWithAttributes:(NSDictionary *)attributes {
    self = [super init];
    if (!self) {
        return nil;
    }
    _mid = [attributes valueForKeyPath:@"mid"];
    _cate = [attributes valueForKeyPath:@"card_type"];
    _owner = [[User alloc] initWithAttributes:attributes];
    _text = [attributes valueForKeyPath:@"text"];
    
    _pic_nums = [NSNumber numberWithInt:[[attributes valueForKey:@"pic_num"] intValue]];
    NSArray *pic_ids = [attributes valueForKey:@"pic_ids"];
    if (pic_ids && [pic_ids count] > 0) {
        NSMutableArray *mutablePics = [NSMutableArray arrayWithCapacity:[pic_ids count]];
        for (NSString *each_id in pic_ids) {
            Pic *pic = [[Pic alloc] initWithPid:each_id];
            [mutablePics addObject:pic];
        }
        _pics = [NSArray arrayWithArray:mutablePics];
    } else {
        _pics = [NSArray array];
    }
    
    _created_time = [attributes valueForKey:@"time"];
    
    _is_collected = NO;
    return self;
}

+ (NSURLSessionDataTask *)tweetsOfCate:(NSString *)cate WithBlock:(void (^)(NSArray *Tweets, NSError *error))block {
    NSDictionary *parameters = @{@"containerid": @"6", @"category":cate, @"count":[NSNumber numberWithInt:(TWEETNum)]};
    return [[BaseApiClient sharedClient] GET:DATA_API_GET parameters:parameters success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSArray *tweetsFromResponse = [[JSON valueForKeyPath:@"data"] valueForKey:@"cards"];
        NSMutableArray *mutableTweets = [NSMutableArray arrayWithCapacity:[tweetsFromResponse count]];
        NSLog(@"%@",tweetsFromResponse);
        for (NSDictionary *attributes in tweetsFromResponse) {
            Tweet *tweet = [[Tweet alloc] initWithAttributes:attributes];
            [mutableTweets addObject:tweet];
        }
        [Collecton checkTweets:mutableTweets AreCollectedByCurrentUserWithBlock:^(NSArray *collect_results, NSError *error){
            if (block) {
                block([NSArray arrayWithArray:mutableTweets], nil);
            }
        }];
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        if (block) {
            block([NSArray array], error);
        }
    }];
}
@end

